package com.leetcode.first50;

/**
 * Created by weishaofei on 2018/11/25.
 */
public class Leetcode0007 {

    public int reverse(int x) {
        if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) {
            return 0;
        }
        if (x > -10 && x < 10) {
            return x;
        }

        String s = String.valueOf(x).replaceAll("-", "");
        String result = "";

        char[] chars = s.toCharArray();
        for (char ch : chars) {
            result = ch + result;
        }
        result = x < 0 ? "-" + result : result;
        if (Long.parseLong(result) > Integer.MAX_VALUE ||
                Long.parseLong(result) < Integer.MIN_VALUE) {
            return 0;
        }
        return Integer.parseInt(result);
    }

    public static void main(String[] args) {
        Leetcode0007 l7 = new Leetcode0007();

        System.out.println(l7.reverse(123));
        System.out.println(l7.reverse(-1123));
        System.out.println(l7.reverse(-1120));
    }
}
